package org.jeecg.gen.javaToSql;

import io.swagger.annotations.ApiModelProperty;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.base.po.EntityBase;

import java.io.*;
import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;


/**
 * @ClassName: SqlGenerator
 * @Description:根据JAVA实体生成SQL建表语句工具
 * @author: zj
 * @date: 2019年10月7日 下午2:09:00
 */
@Slf4j
public class SqlGenerator {

    public static Map<String, String> property2SqlColumnMap = new HashMap<>();

    static {
        property2SqlColumnMap.put("integer", "INT");
        property2SqlColumnMap.put("short", "tinyint");
        property2SqlColumnMap.put("long", "bigint");
        property2SqlColumnMap.put("bigdecimal", "decimal(19,2)");
        property2SqlColumnMap.put("double", "double");
        property2SqlColumnMap.put("float", "float");
        property2SqlColumnMap.put("boolean", "bit");
        property2SqlColumnMap.put("timestamp", "datetime");
        property2SqlColumnMap.put("date", "datetime");
        property2SqlColumnMap.put("string", "VARCHAR(200)");
    }

    public static String generateSql(String className, String tableName, String primaryKey, String filePath) {
        try {
            Class<?> clz = Class.forName(className);
            className = clz.getSimpleName();
            Field[] fields = clz.getDeclaredFields();
            StringBuffer column = new StringBuffer();
            for (Field f : fields) {
                if (f.getName().equals(primaryKey)) {
                    continue;
                }
                // column.append(" \n `"+f.getName()+"`").append(varchar);
                column.append(getColumnSql(f));
            }
//是否增加 EntityBase 基础字段
//			fixEntityBase(primaryKey, column);
            String sqlPrimaryKey = camelToUnderline(primaryKey).toLowerCase();
            StringBuffer sql = new StringBuffer();
            sql.append("\n DROP TABLE IF EXISTS `" + tableName + "`; ")
                    .append(" \n CREATE TABLE `" + tableName + "`  (")
                    .append(" \n `" + sqlPrimaryKey + "` INT(11	) NOT NULL ,").append(" \n " + column)
                    .append(" \n PRIMARY KEY (`" + sqlPrimaryKey + "`)")
                    .append(" \n ) ENGINE = InnoDB   CHARACTER SET = utf8 COLLATE = utf8_general_ci;");
            String sqlText = sql.toString();
            StringToSql(sqlText, filePath);
            return sqlText;
        } catch (ClassNotFoundException e) {
            log.debug("SQL生成异常：", e);
            return null;
        }
    }

    private static void fixEntityBase(String primaryKey, StringBuffer column) {
        Field[] fieldsBase = EntityBase.class.getDeclaredFields();
        for (Field fileBase : fieldsBase) {
            if (fileBase.getName().equals(primaryKey)) {
                continue;
            }
            column.append(getColumnSql(fileBase));
        }
    }

    private static String getColumnSql(Field field) {
        String tpl = "\n `%s` %s DEFAULT NULL COMMENT '%s',";
        String typeName = field.getType().getSimpleName().toLowerCase();
        String sqlType = property2SqlColumnMap.get(typeName);
        if (sqlType == null || sqlType.isEmpty()) {
            log.info(field.getName() + ":" + field.getType().getName() + " 需要单独创建表");
            return "";
        }
        String column = camelToUnderline(field.getName()).toLowerCase();
        String comment = field.getAnnotation(ApiModelProperty.class).value();
        String sql = String.format(tpl, column, sqlType.toUpperCase(), comment);
        return sql;
    }

    private static void StringToSql(String str, String path) {
        byte[] sourceByte = str.getBytes();
        if (null != sourceByte) {
            try {
                File file = new File(path);
                if (!file.exists()) {
                    File dir = new File(file.getParent());
                    dir.mkdirs();
                    file.createNewFile();
                }

//				FileOutputStream outStream = new FileOutputStream(file);
//				outStream.write(sourceByte);
//				outStream.flush();
//				outStream.close();
                method1(path, str);
                System.out.println("生成成功");
            } catch (Exception e) {
                log.debug("保存SQL文件异常：", e);
            }
        }
    }

    /**
     * @param param
     * @return
     * @title: camelToUnderline
     * @description: 驼峰转下划线
     * @return: String
     */
    public static String camelToUnderline(String param) {
        if (param == null || "".equals(param.trim())) {
            return "";
        }
        int len = param.length();
        StringBuilder sb = new StringBuilder(len);
        for (int i = 0; i < len; i++) {
            char c = param.charAt(i);
            if (Character.isUpperCase(c)) {
                sb.append('_');
                sb.append(Character.toLowerCase(c));
            } else {
                sb.append(c);
            }
        }
        return sb.toString();
    }

    /**
     * @param param
     * @return
     * @title: underlineToCamel
     * @description:下划线转驼峰
     * @return: String
     */
    public static String underlineToCamel(String param) {
        if (param == null || "".equals(param.trim())) {
            return "";
        }
        int len = param.length();
        StringBuilder sb = new StringBuilder(len);
        for (int i = 0; i < len; i++) {
            char c = param.charAt(i);
            if (c == '_') {
                if (++i < len) {
                    sb.append(Character.toUpperCase(param.charAt(i)));
                }
            } else {
                sb.append(c);
            }
        }
        return sb.toString();
    }

    public static void method1(String file, String conent) {
        BufferedWriter out = null;
        try {
            out = new BufferedWriter(new OutputStreamWriter(
                    new FileOutputStream(file, true)));
            out.write(conent);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {
        //generateSql(Goods.class.getName(), Goods.class.getSimpleName(), "id", "C:\\Users\\zj\\Desktop\\img\\file1.sql");

        method1("C:\\Users\\zj\\Desktop\\img\\file1.sql", "测试测试将字符写入文件默默");
    }
}